﻿using Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;

namespace DAL
{
    public class BasicDataLoadDAL : BaseDAL
    {
        #region 班级信息表导入
        /// <summary>
        /// 班级信息表导入
        /// </summary>
        /// <returns></returns>
        public bool GetBasicClassInfo()
        {
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                string strBci = string.Empty;
                try
                {
                    strBci = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetBasicClassInfo");
                }
                finally
                {
                    wc.Dispose();
                }
                if (!string.IsNullOrWhiteSpace(strBci))
                {
                    var lbci = JsonConvert.DeserializeObject<List<Model.BasicClassInfo>>(strBci);

                    #region 数据入库
                    using (var conn = new SqlConnection(connection))
                    {
                        conn.Open();
                        conn.Execute("truncate table BasicClassInfo;");
                        IDbTransaction transaction = conn.BeginTransaction();
                        try
                        {
                            lbci.ForEach(bci =>
                            {
                                conn.Execute(" insert into BasicClassInfo(ID,ClassName,GradeInfoId,RoomID,HeadMaster) values (@ID,@ClassName,@GradeInfoId,@RoomID,@HeadMaster)", bci, transaction);
                            });
                            transaction.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Log.errorlog(ex);
                        }
                        conn.Close();
                    }
                    #endregion
                }
            }
            return false;
        }
        #endregion

        #region 班级与教师关联表导入
        /// <summary>
        /// 班级与教师关联表导入
        /// </summary>
        /// <returns></returns>
        public bool GetBasicClassTERelation()
        {
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                string strBcr = string.Empty;
                try
                {
                    strBcr = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetBasicClassTERelation");
                }
                finally
                {
                    wc.Dispose();
                }
                if (!string.IsNullOrWhiteSpace(strBcr))
                {
                    var lbci = JsonConvert.DeserializeObject<List<Model.BasicClassTERelation>>(strBcr);

                    #region 数据入库
                    using (var conn = new SqlConnection(connection))
                    {
                        conn.Open();
                        conn.Execute("truncate table BasicClassTERelation;");
                        IDbTransaction transaction = conn.BeginTransaction();
                        try
                        {
                            lbci.ForEach(bcr =>
                            {
                                conn.Execute("insert into BasicClassTERelation(ID,GradeID,SchoolID,TeacherID,ClassID) values (@ID,@GradeID,@SchoolID,@TeacherID,@ClassID)", bcr, transaction);
                            });
                            transaction.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Log.errorlog(ex);
                        }
                        conn.Close();
                    }
                    #endregion
                }
            }
            return false;
        }
        #endregion

        #region 学校信息表导入
        /// <summary>
        /// 学校信息表导入
        /// </summary>
        /// <returns></returns>
        public bool GetBasicSchoolInfo()
        {
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                string strBcr = string.Empty;
                try
                {
                    strBcr = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetBasicSchoolInfo/" + ConfigHelper.GetConfigString("SchoolID"));
                }
                finally
                {
                    wc.Dispose();
                }
                if (!string.IsNullOrWhiteSpace(strBcr))
                {
                    var lbci = JsonConvert.DeserializeObject<List<Model.BasicSchoolInfo>>(strBcr);

                    #region 数据入库
                    using (var conn = new SqlConnection(connection))
                    {
                        conn.Open();
                        conn.Execute("truncate table BasicSchoolInfo;");
                        IDbTransaction transaction = conn.BeginTransaction();
                        try
                        {
                            lbci.ForEach(bcr =>
                            {
                                conn.Execute("insert into BasicSchoolInfo(ID,SchoolName,AreaId,SchoolAddress,StypeCode,StypeName,Remark,Eable) values (@ID,@SchoolName,@AreaId,@SchoolAddress,@StypeCode,@StypeName,@Remark,@Eable)", bcr, transaction);
                            });
                            transaction.Commit();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            Log.errorlog(ex);
                        }
                        conn.Close();
                    }
                    #endregion
                }
            }
            return false;
        }
        #endregion

        #region 教室信息表导入
        /// <summary>
        /// 教室信息表导入
        /// </summary>
        /// <returns></returns>
        public bool GetBasicRoomInfo()
        {
            Func<int, bool> DownBasicRoomInfo = (roomid) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strBri = string.Empty;
                    try
                    {
                        strBri = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetBasicRoomInfo/" + roomid);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strBri))
                    {
                        var lbri = JsonConvert.DeserializeObject<List<Model.BasicRoomInfo>>(strBri);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            conn.Execute("truncate table BasicRoomInfo;");
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lbri.ForEach(bcr =>
                                {
                                    conn.Execute("insert into BasicRoomInfo(ID,RoomName,Wschool,ServerIP,RoomSeat,RoomArea,Eable,ClientPort,ClientServerIP,ConnectionString) values (@ID,@RoomName,@Wschool,@ServerIP,@RoomSeat,@RoomArea,@Eable,@ClientPort,@ClientServerIP,@ConnectionString)", bcr, transaction);
                                });
                                transaction.Commit();
                                return true;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };

            var RoomIds = ConfigHelper.GetConfigString("RoomID").Split(',');
            if (RoomIds.Length > 0)
            {
                int _rid = 0;
                bool iscompalted = true;
                foreach (var rid in RoomIds)
                {
                    if (int.TryParse(rid, out _rid) && _rid > 0)
                    {
                        iscompalted = iscompalted && DownBasicRoomInfo(_rid);
                    }
                }
                return iscompalted;
            }
            return false;
        }
        #endregion

        #region 学科知识点表导入
        /// <summary>
        /// 学科知识点表导入
        /// </summary>
        /// <returns></returns>
        public bool GetBasicKnowledgepoint()
        {
            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                conn.Execute("truncate table BasicKnowledgepoint;");
            }
            Func<int, int, bool> BasicKnowledgepoint = (pageIndex, pageSize) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strBk = string.Empty;
                    try
                    {
                        strBk = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetBasicKnowledgepoint?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strBk))
                    {
                        var lbk = JsonConvert.DeserializeObject<List<Model.BasicKnowledgepoint>>(strBk);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lbk.ForEach(bk =>
                                {
                                    conn.Execute(" insert into BasicKnowledgepoint(ID,FatherID,BasicFatherID,PointName,SubjectCode,StypeCode) values (@ID,@FatherID,@BasicFatherID,@PointName,@SubjectCode,@StypeCode)", bk, transaction);
                                });
                                transaction.Commit();
                                if (lbk.Count >= pageSize)
                                    return true;
                                else
                                    return false;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };
            bool isGoOn = true;
            int pi = 1, pz = 100;
            do { isGoOn = BasicKnowledgepoint(pi, pz); pi++; } while (isGoOn);
            return true;
        }
        #endregion

        #region 章节表导入
        /// <summary>
        /// 章节表导入
        /// </summary>
        /// <returns></returns>
        public bool GetAllChapter()
        {
            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                conn.Execute("truncate table Chapter;");
            }
            Func<int, int, bool> DownChapter = (pageIndex, pageSize) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strCpt = string.Empty;
                    try
                    {
                        strCpt = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetAllChapter?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strCpt))
                    {
                        var lcpt = JsonConvert.DeserializeObject<List<Model.Chapter>>(strCpt);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lcpt.ForEach(cpt =>
                                {
                                    conn.Execute(" insert into Chapter(ID,FatherID,PointName,Content,TeachingMaterialID) values (@ID,@FatherID,@PointName,@Content,@TeachingMaterialID)", cpt, transaction);
                                });
                                transaction.Commit();
                                if (lcpt.Count >= pageSize)
                                    return true;
                                else
                                    return false;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };
            bool isGoOn = true;
            int pi = 1, pz = 100;
            do { isGoOn = DownChapter(pi, pz); pi++; } while (isGoOn);
            return true;
        }
        #endregion

        #region 教材表导入
        /// <summary>
        /// 教材表导入
        /// </summary>
        /// <returns></returns>
        public bool GetAllTeachingMaterial()
        {
            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                conn.Execute("truncate table TeachingMaterial;");
            }
            Func<int, int, bool> DownTm = (pageIndex, pageSize) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strTm = string.Empty;
                    try
                    {
                        strTm = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetAllTeachingMaterial?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strTm))
                    {
                        var lTm = JsonConvert.DeserializeObject<List<Model.TeachingMaterial>>(strTm);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lTm.ForEach(tm =>
                                {
                                    conn.Execute(@"insert into TeachingMaterial(ID,SubjectCode,GradeCode,Type,Version,SubVersion,UpOrDown,SchoolID) values (@ID,@SubjectCode,@GradeCode,@Type,@Version,@SubVersion,@UpOrDown,@SchoolID)", tm, transaction);
                                });
                                transaction.Commit();
                                if (lTm.Count >= pageSize)
                                    return true;
                                else
                                    return false;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };
            bool isGoOn = true;
            int pi = 1, pz = 100;
            do { isGoOn = DownTm(pi, pz); pi++; } while (isGoOn);
            return true;
        }
        #endregion

        #region 教材绑定表导入
        /// <summary>
        /// 教材绑定表导入
        /// </summary>
        /// <returns></returns>
        public bool GetAllTeachingMaterialBind()
        {
            using (var conn = new SqlConnection(connection))
            {
                conn.Open();
                conn.Execute("truncate table TeachingMaterialBind;");
            }
            Func<int, int, bool> DownTmb = (pageIndex, pageSize) =>
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
                    string strTmb = string.Empty;
                    try
                    {
                        strTmb = wc.DownloadString(ConfigHelper.GetConfigString("RemoteUrl") + "/Ayyfford/GetAllTeachingMaterialBind?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
                    }
                    finally
                    {
                        wc.Dispose();
                    }
                    if (!string.IsNullOrWhiteSpace(strTmb))
                    {
                        var lTm = JsonConvert.DeserializeObject<List<Model.TeachingMaterialBind>>(strTmb);

                        #region 数据入库
                        using (var conn = new SqlConnection(connection))
                        {
                            conn.Open();
                            IDbTransaction transaction = conn.BeginTransaction();
                            try
                            {
                                lTm.ForEach(tm =>
                                {
                                    conn.Execute(@" insert into TeachingMaterialBind(ID,SchoolID,GradeCode,MaterialID,SubjectCode,GradeInfoId) values (@ID,@SchoolID,@GradeCode,@MaterialID,@SubjectCode,@GradeInfoId)", tm, transaction);
                                });
                                transaction.Commit();
                                if (lTm.Count >= pageSize)
                                    return true;
                                else
                                    return false;
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Log.errorlog(ex);
                            }
                            conn.Close();
                        }
                        #endregion
                    }
                }
                return false;
            };
            bool isGoOn = true;
            int pi = 1, pz = 100;
            do { isGoOn = DownTmb(pi, pz); pi++; } while (isGoOn);
            return true;
        }
        #endregion
    }
}
